<?php

namespace App\Library\Service;

use App\Library\Logic\OperateLogLogic;
use App\Library\Logic\ShopUserLogic;
use App\Library\Logic\ShopUserPriceLogic;
use App\Library\Logic\UserDmLogic;
use App\Models\AdminUsersModel;
use App\Models\ShopUserModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class StaffService extends BaseService
{

    /**
     *
     * Author: zlf
     * Created at 2024/11/26 20:22
     * @param $data
     * @return JsonResponse|array
     */
    public function staffList($data): JsonResponse|array
    {
        if (MAINID !== USERID) return failMessage('子账号，无权操作');
        $list = ShopUserModel::query()->where([
            'user_main_id' => USERID,
            'user_type' => 3,
            'user_delete_flag' => 2
        ])->where(function ($query) use ($data) {
            if (!empty($data->keyword)) {
                $query->where('user_mobile', 'like', '%' . $data->keyword . '%');
            }
        });
        return success(paginate($list->orderByDesc('created_at')->paginate($data->limit)));
    }

    public function add($data)
    {
        $mobile = trim($data->mobile);
        if (empty($mobile)) return failMessage('手机号码格式错误');
        else if (!preg_match(__('com.mobileReg'), $mobile)) return failMessage('手机号码格式错误');
        if (MAINID !== USERID) return failMessage('子账号，不能绑定员工帐号');
        $shopUser = ShopUserLogic::findByWhere(['userMobile' => $mobile, 'userDeleteFlag' => 2], null, ['userId', 'userMainId']);
        if (!is_null($shopUser)) {
            if ($shopUser->user_main_id > 0) {
                return failMessage("此帐号已经绑定到用户ID：{$shopUser->user_main_id}，不能重复绑定");
            }
            $shopUser->user_main_id = USERID;
            $shopUser->user_type = 3;//变更为员工
            $shopUser->user_peer_power = 1;
            $shopUser->user_applet_order = 1;
            $shopUser->save();
        } else {
            $secret = random();
            $shopUser = ShopUserLogic::insertForModel([
                'userType' => 3,
                'userMainId' => USERID,
                'userAppletOrder'=>1,
                'userPeerPower'=>1,
                'userNickname' => random(),
                'userName' => $mobile,
                'userMobile' => $mobile,
                'userSecret' => $secret,
                'userPassword' => md5('666666' . $secret),
            ]);
            UserDmLogic::insertForModel('userId', $shopUser->user_id);
            ShopUserPriceLogic::add($shopUser->user_id);
        }
        mq('cacheUser', (string)$shopUser->user_id);
        OperateLogLogic::add(USERID);
        if (!AdminUsersModel::query()->where(['user_id' => $shopUser->user_id])->exists()) {
            $adminModel = AdminUsersModel::insertForModel([
                'user_id' => $shopUser->user_id,
                'user_main_id' => $shopUser->user_main_id ?? 0,
                'username' => $mobile,
                'password' => Hash::make('666666'),
                'name' => $mobile,
                'admin_type' => 1
            ]);
            DB::table('admin_role_users')->insert([
                'role_id' => 3,
                'user_id' => $adminModel->id
            ]);
        }

        return success();
    }

    /**
     *
     * Author: zlf
     * Created at 2024/11/27 15:09
     * @param $data
     * @return JsonResponse
     */
    public function del($data): JsonResponse
    {
        $model = ShopUserModel::query()->where([
            'user_id' => $data->user_id,
            'user_delete_flag' => 2
        ])->first();
        if (empty($model)) return failMessage('无员工信息');
        $model->user_delete_flag = 1;
        $model->delete();
        $model->save();
        $adminInfo = AdminUsersModel::query()->where('user_id', $model->user_id)->first();
        if (!empty($adminInfo)) {
            DB::table('admin_role_users')->where('user_id', $adminInfo->id)->delete();
            $adminInfo->delete();
        }
        return success();
    }
}
